﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMM.Tapioca.Linkbase;
using System.Text.RegularExpressions;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;
using WMM.Tapioca.Utilities;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The specific entity-scheme filter can be used to match facts based upon whether
    /// they report values for the scheme identified by the filter. 
    /// </summary>
    public class SpecificSchemeFilter : Filter
    {
        private string scheme;

        /// <returns> The scheme is the specific entity-scheme filter. </returns>
        public string Scheme
        {
            get { return scheme; }
            set { scheme = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public SpecificSchemeFilter(Resource resource)
            : base(resource)
        {
            string expression = (string)resource.ResourceXElement.Attribute("scheme") ?? string.Empty;
            expression = expression.TrimEnd().TrimStart();
            expression = Regex.Replace(expression, @"\s+", " ");
            scheme = expression;
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            this.dts = dts;
            namespaces = dts.DtsFormula.Namespaces;

            List<FactItem> itemListTemp = new List<FactItem>();

            foreach (FactItem item in itemsToFilter)
            {
                string scheme = EvaluateXPathExpression(Scheme, item.ContextRef.ContextElement.ToXmlNode());

                if (Complement ? !scheme.Equals(item.ContextRef.IdentifierScheme) : scheme.Equals(item.ContextRef.IdentifierScheme))
                {
                    itemListTemp.Add(item);
                }
            }

            return itemListTemp;
        }
    }
}
